package com.example.helloandroid.rest.client;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import android.util.Log;

import com.example.helloandroid.beans.AccountDTO;

public class AccountRestClientImpl extends GenericRestClient implements AccountRestClient {

	private static final String TAG = "HelloAndroid";
	
	public AccountDTO getBalanceFromIdConto(String idConto) throws Exception {
		String result = "";
		GetMethod httpget = null;
		AccountDTO accountDTO = new AccountDTO();
		try {
			Serializer serializer = new Persister();
			
			HttpClient httpclient = new HttpClient();
			httpget = new GetMethod(getRestBaseUrl() + "/account/balanceFromIdConto/" + idConto);							
			httpget.addRequestHeader("content-type", "text/xml");
			httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
			httpclient.executeMethod(httpget);
			result = httpget.getResponseBodyAsString();
			if ( HttpStatus.SC_OK != httpget.getStatusCode() ){
				throw new Exception("Error on calling rest server, error code: " + httpget.getStatusCode());
			}
			accountDTO = serializer.read(AccountDTO.class, result);
		} catch (HttpException he) {
			Log.v(TAG, "HttpException was thrown!! Error message : " + he.getMessage(), he);
			result = he.getMessage();
		} catch (IOException ioe) {
			Log.v(TAG, "IOException was thrown!! Error message : " + ioe.getMessage(), ioe);
			result = ioe.getMessage();
		} catch (Exception e) {
			Log.v(TAG, "Exception was thrown!! Error message : " + e.getMessage(), e);
			result = e.getMessage();
		} finally {
			if ( httpget != null ){
				httpget.releaseConnection();
			}
		}
		return accountDTO;
	}
}
